package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedissonClient redissonClient;
    public static final DefaultRedisScript<Long> seckill_script;
    static {
        seckill_script = new DefaultRedisScript<>();
        seckill_script.setResultType(Long.class);
        seckill_script.setLocation(new ClassPathResource("seckill.lua"));
    }
    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService SECKILL_EXECUTOR= Executors.newSingleThreadExecutor();
    private  IVoucherOrderService proxy;
    @PostConstruct
    private void init(){
//        SECKILL_EXECUTOR.submit(new VoucherOrderHandle());
    }

    class VoucherOrderHandle implements Runnable{

        @Override
        public void run() {
            while (true){

                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }


            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        RLock lock = redissonClient.getLock("lock:order:"+userId);
        boolean success = lock.tryLock();
        if(!success){
            log.error("不允许重复下单");
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }
   /* public Result seckillVoucher(Long voucherId) {
        //判断购买资格
        Long userId = UserHolder.getUser().getId();
        //redis里么存入数值就不要有回车 否则就转换数值有问题
        Long result = stringRedisTemplate.execute(seckill_script,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        int r = result.intValue();
        if(r!=0){
            return Result.fail(r==1?"库存不足":"不允许重复下单");
        }
        // 生成订单放入阻塞队列
        long orderId = redisIdWorker.nextId("order");
        //生成订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        voucherOrder.setId(orderId);
        IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
        proxy.createVoucherOrder(voucherOrder);
        //返回订单id
        return Result.ok(orderId);

    }*/



    public Result seckillVoucher(Long voucherId) {
       //判断购买资格
        Long userId = UserHolder.getUser().getId();
        //redis里么存入数值就不要有回车 否则就转换数值有问题
        Long result = stringRedisTemplate.execute(seckill_script,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        int r = result.intValue();
        if(r!=0){
            return Result.fail(r==1?"库存不足":"不允许重复下单");
        }
        // 生成订单放入阻塞队列
        long orderId = redisIdWorker.nextId("order");
        //生成订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userId);
        voucherOrder.setId(orderId);
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//        orderTasks.add(voucherOrder);
        String queueName="hmdp.queue1";
        rabbitTemplate.convertAndSend(queueName,voucherOrder);
        //返回订单id
        return Result.ok(orderId);

    }
/*
    public Result seckillVoucher(Long voucherId) {
        //获取优惠卷信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //判断优惠券时间
        Long userId = UserHolder.getUser().getId();
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        LocalDateTime endTime = seckillVoucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();
        if(beginTime.isAfter(now)||endTime.isBefore(now)){
            return Result.fail("不在活动时间内");
        }
        //判断优惠卷库存，扣减库存
        Integer stock = seckillVoucher.getStock();
        if(stock<1){
            return Result.fail("库存不足");
        }
//        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order:" + userId);
        RLock lock = redissonClient.getLock("lock:order:"+userId);
        boolean success = lock.tryLock();
        if(!success){
            return Result.fail("不允许重复下单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId, userId);
        } finally {
            lock.unlock();
        }
*/


    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long voucherId = voucherOrder.getVoucherId();
        boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherId)
                    .gt("stock",0)
                    .update();
        if(!success){
            log.error("库存不足");
        }
            //生成订单
        save(voucherOrder);
    }

}
